/*
 * CKFinder
 * ========
 * http://cksource.com/ckfinder
 * Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
 *
 * The software, this file and its contents are subject to the CKFinder
 * License. Please read the license.txt file before using, installing, copying,
 * modifying or distribute this file or part of its contents. The contents of
 * this file is part of the Source Code of CKFinder.
 */
package com.ls.fw.web.file.config;

import javax.servlet.ServletConfig;

import org.apache.commons.lang3.StringUtils;

import com.ckfinder.connector.configuration.Configuration;
import com.ckfinder.connector.configuration.ConfigurationPathBuilder;
import com.ckfinder.connector.configuration.IBasePathBuilder;
import com.ckfinder.connector.utils.PathUtils;
import com.ls.fw.commons.spring.SpringContextHolder;
import com.ls.fw.web.file.support.config.IFileConfiguration;

/**
 * Class loads configuration from XML file.
 */
public class FwConfiguration extends Configuration {

	
	/**
	 * @param servletConfig
	 */
	public FwConfiguration(ServletConfig servletConfig) {
		super(servletConfig);
	}

	@Override
	public void init() throws Exception {
		// TODO Auto-generated method stub
		super.init();
		String className = servletConf.getInitParameter(
					"basePathBuilderImpl");
		if (StringUtils.isNotBlank(className)) {
			setBasePathImpl(className);
		}
		IFileConfiguration fileConfiguration  =  SpringContextHolder.getBean(IFileConfiguration.class);
//		RequestMapping requestMapping = FileController.class.getAnnotation(
//				RequestMapping.class);
//		final String pathString = requestMapping.value()[0] + IFileConfiguration.DEFAULT_DOWNLOAD_BASE_URL;
//		fileConfiguration.setDownloadFunPath(pathString);
		
		baseDir = fileConfiguration.getBaseDir();
		this.baseDir = PathUtils.escape(this.baseDir);
		this.baseDir = PathUtils.addSlashToEnd(this.baseDir);

		baseURL = fileConfiguration.getBaseUrl();
		this.baseURL = PathUtils.escape(baseURL);
		this.baseURL = PathUtils.addSlashToEnd(this.baseURL);
		
//		if(defaultResourceTypes != null){
//			for (String type : defaultResourceTypes) {
//				String filesDir = types.get(type).getPath();
//				filesDir =  StringUtils.replace(filesDir, "%BASE_DIR%", "");
//				fileConfiguration.setAppendBaseDir(filesDir);
//				break;
//			}
//		}
	}
	protected void setBasePathImpl(final String value) {
		try {
			@SuppressWarnings("unchecked")
			Class<IBasePathBuilder> clazz = (Class<IBasePathBuilder>) Class.forName(value);
			this.basePathBuilder = clazz.newInstance();
		} catch (Exception e) {
			this.basePathBuilder = new ConfigurationPathBuilder();
		}
	}

}
